#include "head.h"
#include "fun.h"
int main()
{
    Config config; // 定义配置文件结构体
    char config_path[1024] = "config.ini";
    if (access(config_path, F_OK) == -1)
    { // 检查文件是否存在
        printf("配置文件 config.ini 不存在，请创建后重试！\n");
        exit(EXIT_FAILURE);
    }
    get_config(config_path, &config); // 动态加载配置
    printf("%s", config.ip);
    printf("%d", config.port);
    // 1创建客户端套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sockfd, -1, "socket");

    struct sockaddr_in serveraddr;
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(config.port);
    serveraddr.sin_addr.s_addr = inet_addr(config.ip);

    int ret = connect(sockfd,
                      (const struct sockaddr *)&serveraddr,
                      sizeof(serveraddr));
    ERROR_CHECK(ret, -1, "connect");
    printf("================= 连接到服务器 ================\n");
    printf("================= IP:%s ============\n", config.ip);
    printf("================= 端口号:%d =================\n", config.port);

    // 登录
    while (1)
    {
        if (login(sockfd) == 0)
        {
            break;
        }
    }

    train_t t;
    int flag = -1;
    int data_len = 0;
    char name[20] = {0};
    char *passwd;
    char path[256] = {0};
    print_options();
    printf("登录成功：\n");
    printf("当前路径：");
    // 接收绝对路径
    ret = recvn(sockfd, &data_len, 4);
    ERROR_CHECK(ret, -1, "recvn");
    ret = recvn(sockfd, &path, data_len);
    ERROR_CHECK(ret, -1, "recvn");
    puts(path);
    while (1)
    {
        if (command_run(sockfd, path) == 1)
        {
            break; // 如果返回1，表示退出
        }
    }
    // 执行程序

    close(sockfd);

    return 0;
}
